<?php
/**
 * Description: 模考说明页面数据接口
 * User: devforma
 * Date: 15/9/16
 * Time: 14:56
 */

class GetMockTutorial implements iController {
    private $unpurchasedUrl, $purchasedUrl;

    public function __construct() {
        $this->unpurchasedUrl = YG_MOBILE_SECURE_URL . '/index.html#/live/unpurchased?course_id=';
        $this->purchasedUrl = YG_MOBILE_SECURE_URL . '/index.html#/live/purchased?course_id=';
    }

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $cmsdb, $uddb;

        if (empty($queryArgs['mock_id']) || !filter_var($queryArgs['mock_id'], FILTER_VALIDATE_INT))
            return genOutput(1000);

        $hasUser = (validateUser($queryArgs) === 1);

        if ($tutorial = $this->getTutorial($queryArgs['mock_id'])) {
            $dateInfo = array();

            $lines = explode('#', $tutorial['examDate']);
            $courseId = 0;
            $isPurchased = false;
            foreach ($lines as $line) {
                $count = preg_match('/\*([0-9]+)\*/', $line, $match);
                if ($count) {
                    if ($hasUser) {
                        $isPurchased = $this->checkPurchase($queryArgs['user_id'], $match[1]);
                    }
                    $link = $isPurchased ? $this->purchasedUrl . $match[1] : $this->unpurchasedUrl . $match[1];
                    $courseId = $match[1];
                    $dateInfo[] = array('text' => str_replace($match[0], '', $line), 'link' => $link);
                } else {
                    $dateInfo[] = array('text' => $line, 'link' => '');
                }
            }

            //多试卷情况
            if (!empty($tutorial['related_ids'])) {
                $idStr = $queryArgs['mock_id'] . ',' .$tutorial['related_ids'];
            } else {
                $idStr = $queryArgs['mock_id'];
            }

            //是否已完成
            if ($hasUser) {
                $exists = $cmsdb->getVar("SELECT `id` FROM `qb_relationship_user_paper` WHERE `user_id`=:uid AND `paper_id` IN ({$idStr}) AND `paper_type`=8",
                    array(':uid' => $queryArgs['user_id']));

                //是否预约
                $booked = $uddb->getVar('SELECT `id` FROM `book_mock_users` WHERE `user_id`=:uid AND `mock_id`=:mid LIMIT 1',
                    array(':uid' => $queryArgs['user_id'], ':mid' => $queryArgs['mock_id']));
            } else {
                $exists = 0;
                $booked = 0;
            }

            /* 2015-10-28 模考开考时间随机化，防止网络拥堵 */
            $startTime = strtotime($tutorial['startTime']) + rand(0, 15);
            $duration = $cmsdb->getVar('SELECT `duration` FROM `data_test_paper` WHERE `id`=:id', array(':id' => $queryArgs['mock_id']));

            return genOutput(1, array(
                'mock_time' => date('Y-m-d H:i:s', $startTime),
                'mock_status' => $this->getMockStatus($startTime, $duration),
                'date_info' => $dateInfo,
                'list_intro' => (string)$tutorial['related_intro'],
                'award_info' => explode('#', $tutorial['pride']),
                'course_id' => intval($courseId),
                'is_purchased' => $isPurchased,
                'is_booked' => empty($booked) ? false : true,
                'download_link' => empty($tutorial['downloadLink']) ? '' : $tutorial['downloadLink'],
                'exercise_id' => !empty($exists) ? intval($exists) : 0,
                'mock_list' => !empty($tutorial['papers']) ? $tutorial['papers'] : []
            ));
        }

        return genOutput(1001);
    }

    private function getMockStatus($startTime, $duration) {
        $now = time();

        if ($now < $startTime)
            return 'unstart';

        elseif ($startTime <= $now && $now <= $startTime + 30*60)
            return 'on_going';

        elseif ($startTime + 30*60 < $now && $now < $startTime + $duration)
            return 'end';

        else
            return 'finish';
    }

    private function checkPurchase($userId, $courseId) {
        global $cmsdb;

        $purchased = $cmsdb->getVar('SELECT `id` FROM `relation_user_product` WHERE `user_id`=:uid AND `product_id`=:pid AND `product_type`="zhiboke"',
            array(':uid' => $userId, ':pid' => $courseId));

        return !empty($purchased);
    }

    private function getTutorial($mockId) {
        global $cmsdb;
        $cacheKey = 'mockTutorial:' . $mockId;

        if (($value = cacheGet($cacheKey)) == null) {
            $value = $cmsdb->getVar('SELECT `paper_customed_detail` FROM `data_test_paper` WHERE `id`=:id',
                array(':id' => $mockId));

            if (empty($value))
                return false;

            //多试卷情况
            if (($value = unserialize($value)) && !empty($value['related_ids'])) {
                $idStr = $mockId . ',' . $value['related_ids'];

                $list = [];
                $papers = $cmsdb->getResults("SELECT `id`, `paper_name`, `question_num` FROM `data_test_paper` WHERE `id` IN ({$idStr}) ORDER BY FIELD (`id`, {$idStr})");
                foreach ($papers as $p) {
                    $list[] = [
                        'paper_id'      => (int)$p->id,
                        'paper_name'    => $p->paper_name,
                        'question_num'  => (int)$p->question_num
                    ];
                }
                $value['papers'] = $list;
            }

            cacheSet($cacheKey, $value, 60*60);
        }

        return $value;
    }
}